package com.league.zjxn.main.home

import com.blankj.utilcode.util.SPStaticUtils
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.league.zjxn.R
import com.league.zjxn.jetpack.vmodel.BUNDLE_KEY_SEARCH
import com.league.zjxn.jetpack.vmodel.SearchViewModel
import com.league.zjxn.main.adapter.HomeSearchLabelAdapter
import com.module.lemlin.owner.OwnerViewModeFragment
import kotlinx.android.synthetic.main.fragment_search_record.*

class SearchRecordFragment : OwnerViewModeFragment<SearchViewModel>() {

    companion object {
        fun newInstance(): SearchRecordFragment {
            return SearchRecordFragment()
        }
    }

    private val mHomeSearchRecordAdapter = HomeSearchLabelAdapter()


    override fun viewModel(): SearchViewModel {
        return createViewModel(requireActivity())
    }

    override val layoutResId: Int
        get() = R.layout.fragment_search_record

    override fun initView() {
        rvSearchRecordRecordBody.apply {
            val layoutManager = FlexboxLayoutManager(
                requireContext(), FlexDirection.ROW, FlexWrap.WRAP
            )
            this.layoutManager = layoutManager
        }.adapter = mHomeSearchRecordAdapter.apply {
            setOnItemClickListener { _, _, position ->
                viewModel.keywordLiveData.postValue(data[position])
            }
        }

        ivSearchRecordClear.setOnClickListener {
            SPStaticUtils.remove(BUNDLE_KEY_SEARCH)
            viewModel.searchRecord()
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden)
            return
        viewModel.searchRecord()
    }

    override fun initViewMode() {
        viewModel.searchRecordLiveData.observe(viewLifecycleOwner, { record ->
            if (record.isNullOrEmpty()) {
            } else {
                mHomeSearchRecordAdapter.setNewInstance(record)
            }
        })

    }
}